<template>
    <!-- 高压系统 -->
    <div class="moduleBox" v-cloak>
        <div class="statisticsBox" v-if="pageData.switchover">
            <div class="title">绩效统计</div>
            <div class="listBoxs">
                <div class="topmsgbox" :class="pageData.selectTr ? 'topmsgboxActive' : ''">
                    <div class="time">
                        <span>
                            轨迹时段：
                            {{ pageData.selectTr ? `${pageData.selectTr.timeIntervalStart}:00` : "" }}
                            -
                            {{ pageData.selectTr ? `${pageData.selectTr.timeIntervalEnd}:00` : "" }}
                        </span>
                        <span>日期：{{ pageData.selectTr ? pageData.selectTr.rq : "" }}</span>
                    </div>
                    <div class="staTip">
                        <div>行距：{{ pageData.selectTr ? pageData.selectTr.lineSpacing : 0 }}米</div>
                    </div>
                </div>
                <div class="tablesBox">
                    <el-scrollbar class="tablesscrollbar">
                        <table class="tables" cellpadding="0" cellspacing="0">
                            <tr>
                                <td>姓名</td>
                                <td>状态</td>
                                <td>运动距离</td>
                                <td>扫略面积</td>
                                <td>工作评论</td>
                            </tr>
                            <tr v-for="item in pageData.menbers" :key="item" class="tableItem" :class="pageData.selectTr != undefined && pageData.selectTr.id == item.id ? 'serlectTableTr' : ''" @click="clicks(item)">
                                <td class="pl">
                                    <div class="tdcell">
                                        {{ item.name }}
                                    </div>
                                </td>
                                <td>
                                    <div class="tdcell">
                                        {{ item.deviceOnlineStatus ? "在线" : "离线" }}
                                    </div>
                                </td>
                                <td>
                                    <div class="tdcell">{{ Number(item.movementDistance) > 1000 ? (Number(item.movementDistance) / 1000).toFixed(2) : item.movementDistance }}{{ Number(item.movementDistance) > 1000 ? "千米" : "米" }}</div>
                                </td>
                                <td>
                                    <div class="tdcell">{{ item.ccanningArea }}亩</div>
                                </td>
                                <td class="pr">
                                    <div class="tdcell">
                                        <select name="" id="" v-if="pageData.selectTr && pageData.selectTr.id == item.id" v-model="item.workReview" @click.stop @change="evaluate" style="width: 0.53rem; height: 0.22rem; padding: 0">
                                            <option value="优">优</option>
                                            <option value="良">良</option>
                                            <option value="中">中</option>
                                            <option value="差">差</option>
                                        </select>
                                        <span v-else>
                                            {{ item.workReview }}
                                        </span>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </el-scrollbar>
                </div>
                <div class="btnBox">
                    <div>
                        <div class="btn" @click="cutDoc()" v-if="pageData.selectTr != undefined">人员管理</div>
                    </div>
                    <div class="rightBtn">
                        <div class="btn" v-if="pageData.selectTr == undefined" @click="cutDoc()">添加</div>
                        <div class="btn" v-else @click="removeMenbers">删除</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="statisticsBox" v-else>
            <div class="title">人员管理</div>
            <div class="msgBox highpressure">
                <div class="msgtablesBox">
                    <table class="msgtables" cellpadding="0" cellspacing="0">
                        <tr>
                            <td>设备选择：</td>
                            <td>
                                <select name="" id="" class="selectBox" v-model="pageData.postMsg.deviceId">
                                    <option disabled value="">请选择</option>
                                    <option :value="item.deviceId" v-for="(item, index) in pageData.deviceList" :key="index">
                                        {{ item.deviceName }}
                                    </option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td>人员姓名：</td>
                            <td>
                                <input type="text" v-model="pageData.postMsg.name" placeholder="请输入人员姓名" />
                            </td>
                        </tr>
                        <tr>
                            <td>工作日期：</td>
                            <td>
                                <input type="date" name="date" v-model="pageData.postMsg.rq" id="" />
                            </td>
                        </tr>
                        <tr>
                            <td>工作时段：</td>
                            <td>
                                <select name="time" id="" v-model="pageData.postMsg.timeIntervalStart">
                                    <option disabled value="">请选择</option>
                                    <option v-for="item = 0 in 24" :value="item - 1">
                                        {{ item - 1 < 10 ? `0${item - 1}:00` : `${item - 1}:00` }}
                                    </option>
                                </select>
                                <span class="interval">-</span>
                                <select name="time" id="" v-model="pageData.postMsg.timeIntervalEnd">
                                    <option disabled value="">请选择</option>
                                    <option v-for="item = 0 in 24" :value="item - 1">
                                        {{ item - 1 < 10 ? `0${item - 1}:00` : `${item - 1}:00` }}
                                    </option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td>栽培行距：</td>
                            <td>
                                <div class="inputNumber">
                                    <input type="number" name="number" min="0" v-model="pageData.postMsg.lineSpacing" step="0.01" />
                                    <div class="unit">米</div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>栽培株距：</td>
                            <td>
                                <div class="inputNumber">
                                    <input type="number" name="number" min="0" v-model="pageData.postMsg.rowSpacing" step="0.01" />
                                    <div class="unit">株</div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>工作内容：</td>
                            <td>
                                <input type="text" v-model="pageData.postMsg.jobContent" placeholder="请输入工作内容" />
                            </td>
                        </tr>
                        <tr>
                            <td>工作要求：</td>
                            <td>
                                <textarea name="textarea" v-model="pageData.postMsg.jobRequirement" cols="30" rows="4" placeholder="请输入工作要求"></textarea>
                            </td>
                        </tr>
                        <!-- <tr>
                        <td colspan="2">
                            <div class="btnBox">
                                <div></div>
                                <div class="rightBtn">
                                    <div class="btn" v-if="pageData.selectTr == undefined && pageData.postMsg.deviceId" @click="equipmenttest()">测试</div>
                                    <div class="btn" @click="addDevice">
                                        {{ pageData.selectTr == undefined ? "添加" : "保存" }}
                                    </div>
                                    <div class="btn" @click="cutDoc()">返回</div>
                                </div>
                            </div>
                        </td>
                    </tr> -->
                    </table>
                </div>

                <div class="btnBox">
                    <div></div>
                    <div class="rightBtn">
                        <div class="btn" v-if="pageData.selectTr == undefined && pageData.postMsg.deviceId" @click="equipmenttest()">测试</div>
                        <div class="btn" @click="addDevice">
                            {{ pageData.selectTr == undefined ? "添加" : "保存" }}
                        </div>
                        <div class="btn" @click="cutDoc()">返回</div>
                    </div>
                </div>
            </div>
        </div>
        <!-- <div class="chartBox" :class="pageData.selectTr ? 'chartBoxShows' : ''"> -->
        <div class="chartBox chartBoxShows">
            <div class="title">
                {{ pageData.equipmenttest ? "设备测试" : "工作考核" }}
            </div>
            <div class="chartBoxCont">
                <div class="time">
                    <span>员工姓名：{{ pageData.selectTr ? pageData.selectTr.name : "" }}</span>
                    <span>当前速度：{{ pageData.selectTr ? pageData.selectTr.speed : "0" }}m/s</span>
                </div>
                <echarts ref="echartsDoc" :key="pageData.echartsKey"></echarts>
            </div>
        </div>
        <operation></operation>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import operation from "@/views/operation/operation.vue";
import maps from "@/utils/initMap";
import echarts from "@/views/echarts/echarts.vue";
import { getDeviceList, addMenber, getMenbers, updateMenber, removeMenber, setLocation, getLocation } from "@/api/api";
import { getOptions, menberVerify, popMsg, jobTimes, highpressure } from "@/utils/tools";
const pageData: any = reactive({
    switchover: true, // 是否打开人员列表页
    equipmenttest: false, // 是否测试设备
    echartsKey: new Date().getTime(), // 更新echarts
    echartsData: [1], // echarts数据
    echartsYaxisData: [1], // echarts Y轴数据-时间段
    deviceList: [], // 设备列表
    postMsg: {
        rowSpacing: 0, // 株距
        timeIntervalStart: "0", // 开始时间
        timeIntervalEnd: "0", // 结束时间
        name: "", // 姓名
        lineSpacing: 0, // 行距
        deviceOnlineStatus: "0", // 设备是否在线
        deviceId: "", // 设备
        deviceName: "", // 设备
        movementDistance: 0,
        ccanningArea: 0,
        workReview: "优",
        reviewer: "",
        reviewTime: "",
        speed: "0",
        dataStatus: "1",
        rq: "", // 工作日期
        jobContent: "", // 工作内容
        jobRequirement: "", // 工作要求
    },
    timer: undefined, // 定时器
    menbers: [], // 人员列表
    selectTr: undefined, // 选择的TR  列表数据
    menberTimer: null,
});
const echartsDoc: any = ref(null);
let location: any = [];
// onMounted(() => {
//     console.log(echartsDoc);
// });
/**
 * tabel点击函数，
 * @param item 选中的item
 */
const clicks = (item: any) => {
    console.log(item);
    if (pageData.selectTr == undefined || pageData.selectTr.id != item.id) {
        pageData.selectTr = item;
        pageData.echartsKey = new Date().getTime();
        location = [];
        getLocations();
        // 设备在线
        if (item.deviceOnlineStatus) {
            endmenberTimer();
            getDeviceLocaOption((data: any) => {
                console.log(data, 11);
                // if (data.location) {
                setEchatrs(data);
                startGetOption();
                // }
            });
        } else {
            setEchatrs("");
            // startGetOption();
        }
    } else {
        pageData.selectTr = undefined;
        startmenberTimer();
    }
};
// 设置图表参数
const setEchatrs = (data: any) => {
    if (data && pageData.selectTr != undefined) {
        data.forEach((d: any) => {
            if (d.mobileNo == pageData.selectTr.deviceId) {
                let speed = d.location ? d.location.speedKph : 0;
                pageData.selectTr.speed = speed;
                setTimeout(() => {
                    console.log(echartsDoc.value);
                    // if (echartsDoc.value) {
                    echartsDoc.value?.setData(speed, highpressure());
                    // }
                }, 300);
                // 地图划线
                if (d.location) {
                    let opt = [d.location.lng, d.location.lat, 0];
                    location.push(opt);
                    maps.setTrack(location, (length: any) => {
                        console.log(length, "线段长度");
                        pageData.selectTr.movementDistance = length.toFixed(2); // 运动距离
                        pageData.selectTr.ccanningArea = ((Number(pageData.selectTr.lineSpacing) * Number(length.toFixed(2))) / 666.67).toFixed(2); // 扫略面积
                        pageData.postMsg = JSON.parse(JSON.stringify(pageData.selectTr));
                        updateMenber(pageData.postMsg).then((res) => {});
                    });
                    setLocations(d);
                }
            }
        });
    } else {
        echartsDoc.value.setData(0, highpressure());
    }
};
// 保存设备坐标
const setLocations = (data: any) => {
    let pd = {
        personnelId: pageData.selectTr ? pageData.selectTr.id : "",
        latitude: "",
        longitude: "",
        speed: 0,
        deviceTime: "",
        lng: data.location.lng,
        lat: data.location.lat,
        deviceId: data.mobileNo,
    };
    console.log(pd, "91919191", pageData.selectTr);
    setLocation(pd);
};
// setTimeout(() => {
//     setLocations({});
// }, 3000);
// 获取设备坐标位置
const getLocations = () => {
    getLocation(pageData.selectTr.id, pageData.selectTr.deviceId).then((res) => {
        let data = res.data;
        data.forEach((d: any) => {
            let opt = [d.lng, d.lat, 0];
            location.push(opt);
        });
        maps.setTrack(location, (length: any) => {
            console.log(length, "线段长度");
            pageData.selectTr.movementDistance = length.toFixed(2); // 运动距离
            pageData.selectTr.ccanningArea = ((Number(pageData.selectTr.lineSpacing) * Number(length.toFixed(2))) / 666.67).toFixed(2); // 扫略面积
            pageData.postMsg = JSON.parse(JSON.stringify(pageData.selectTr));
            updateMenber(pageData.postMsg).then((res) => {});
        });
    });
};
// 开始获取定位
const startGetOption = () => {
    pageData.timer = setInterval(() => {
        getDeviceLocaOption((data: any) => {
            // 设备实时在线状态
            pageData.menbers.forEach((m: any, mi: number) => {
                if (data.length > 0) {
                    data.forEach((d: any, di: number) => {
                        if (m.deviceId == d.mobileNo) {
                            m.deviceOnlineStatus = 1;
                        } else {
                            m.deviceOnlineStatus = 0;
                        }
                    });
                } else {
                    m.deviceOnlineStatus = 0;
                }
            });
            // 设置参数
            setEchatrs(data);
            // let speed = data.location.speed;
            // echartsDoc.value.setData(speed, highpressure());
            // pageData.echartsYaxisData.push(highpressure());
            // pageData.echartsData.push(0);
            // pageData.echartsKey = new Date().getTime();
        });
    }, 5000);
    // 20000
};

const cutDoc = () => {
    pageData.switchover = !pageData.switchover;
    if (!pageData.switchover && pageData.selectTr) {
        // 人员编辑
        console.log(pageData.selectTr);
        pageData.selectTr.timeIntervalStart = parseInt(pageData.selectTr.timeIntervalStart);
        pageData.selectTr.timeIntervalEnd = parseInt(pageData.selectTr.timeIntervalEnd);
        // pageData.postMsg = pageData.selectTr;
        pageData.postMsg = JSON.parse(JSON.stringify(pageData.selectTr));
    }
};
// 测试设备是否在线
const equipmenttest = () => {
    if (pageData.postMsg.deviceId) {
        getDeviceLocaOption((data: any) => {
            console.log(data);
            if (data.length > 0) {
                data.forEach((v: any, i: number) => {
                    if (v.mobileNo == pageData.postMsg.deviceId) {
                        popMsg.success("当前设备在线，可以进行下一步操作！");
                        pageData.equipmenttest = true;
                        pageData.postMsg.deviceOnlineStatus = "1";
                    } else {
                        popMsg.error("当前设备不在线，请稍后再试！");
                    }
                });
            } else {
                popMsg.error("当前设备不在线，请稍后再试！");
            }
        });
    } else {
        popMsg.error("请先选择设备！");
    }
};
/**
 * 工作评价
 */
const evaluate = () => {
    console.log(pageData.selectTr);
    // 修改人员信息
    updateMenber(pageData.selectTr).then((res) => {
        popMsg.success("评价成功");
    });
};
/**
 * 添加成员-修改
 */
const addDevice = () => {
    if (menberVerify(pageData.postMsg)) {
        if (pageData.selectTr) {
            // 修改人员信息
            console.log(pageData.postMsg, "提交最新数据");
            if (pageData.selectTr.id) {
                pageData.postMsg.id = pageData.selectTr.id;
            }
            updateMenber(pageData.postMsg).then((res) => {
                popMsg.success("修改成功");
                getAllMenbers();
                // 更新已有数据
                pageData.selectTr = JSON.parse(JSON.stringify(pageData.postMsg));
                pageData.equipmenttest = false;
                pageData.switchover = true;
            });
        } else {
            // 添加人员
            // 判断是否经过设备在线测试
            if (pageData.equipmenttest && pageData.postMsg.deviceOnlineStatus == "1") {
                addMenber(pageData.postMsg).then((res) => {
                    popMsg.success("添加成功");
                    getAllMenbers();
                    pageData.equipmenttest = false;
                    pageData.switchover = true;
                });
            } else {
                // alert("请先测试设备是否在线！");

                ElMessageBox.alert("请先测试设备是否在线！", "", {
                    closeOnClickModal: false, // 是否可以通过点击遮罩层来关闭对话框
                    showConfirmButton: true,
                });
            }
        }
    }
};
// 删除人员
const removeMenbers = () => {
    let mystr = confirm("确定要删除该人员吗?");
    if (mystr == true) {
        removeMenber({ id: pageData.selectTr.id }).then((res) => {
            popMsg.success("删除成功！");
            pageData.selectTr = undefined;
            getAllMenbers();
        });
    }
};
/**
 * 获取人员列表
 */
const getAllMenbers = () => {
    getMenbers().then((res) => {
        pageData.menbers = res.data;
        // if (pageData.menbers.length > 0) {
        //     // 默认选择第一个
        //     setTimeout(() => {
        //         clicks(pageData.menbers[0]);
        //     }, 1000);
        // }
        getDeviceLocaOption((data: any) => {
            // 判断设备在线状态
            pageData.menbers.forEach((m: any, mi: number) => {
                if (data.length > 0) {
                    data.forEach((d: any, di: number) => {
                        if (m.deviceId == d.mobileNo) {
                            m.deviceOnlineStatus = 1;
                        } else {
                            m.deviceOnlineStatus = 0;
                        }
                    });
                } else {
                    m.deviceOnlineStatus = 0;
                }
            });
        });
    });
};
getAllMenbers();
const startmenberTimer = () => {
    pageData.menberTimer = setInterval(() => {
        getDeviceLocaOption((data: any) => {
            // 判断设备在线状态
            pageData.menbers.forEach((m: any, mi: number) => {
                if (data.length > 0) {
                    data.forEach((d: any, di: number) => {
                        if (m.deviceId == d.mobileNo) {
                            m.deviceOnlineStatus = 1;
                            endmenberTimer();
                            if (pageData.selectTr) {
                                clicks(m);
                            }
                        } else {
                            m.deviceOnlineStatus = 0;
                        }
                    });
                } else {
                    m.deviceOnlineStatus = 0;
                    // setEchatrs("");
                }
            });
        });
    }, 5000);
};
startmenberTimer();
const endmenberTimer = () => {
    clearInterval(pageData.menberTimer);
};
/**
 * 获取设备定位信息
 */
const getDeviceLocaOption = (callback: Function) => {
    getOptions().then((res: any) => {
        callback(res.data);
    });
};
// 获取设备列表
getDeviceList().then((res) => {
    pageData.deviceList = res.data;
    if (res.data.length > 0) {
        // pageData.postMsg.deviceId = res.data[0].deviceId;
        // pageData.postMsg.deviceName = res.data[0].deviceName;
    }
});
// 监听关闭人员信息页,回复参数初始值
watch(
    () => pageData.switchover,
    (newCount, oldCount) => {
        if (newCount) {
            pageData.postMsg.rowSpacing = 0;
            pageData.postMsg.timeIntervalStart = "";
            pageData.postMsg.timeIntervalEnd = "";
            pageData.postMsg.name = "";
            pageData.postMsg.lineSpacing = 0;
            pageData.postMsg.deviceOnlineStatus = "0";
            pageData.postMsg.deviceId = "";
            pageData.postMsg.deviceName = "";
            pageData.postMsg.movementDistance = 4;
            pageData.postMsg.ccanningArea = 0;
            pageData.postMsg.workReview = "优";
            pageData.postMsg.reviewer = "";
            pageData.postMsg.reviewTime = "";
            pageData.postMsg.dataStatus = "1";
            pageData.postMsg.rq = "";
            pageData.postMsg.jobContent = "";
            pageData.postMsg.jobRequirement = "";
        }
        console.log(pageData.selectTr);
    }
);
</script>
